<?php
/**
 * // Set supply weight
 * $rate = new RateTH(1167);
 * // Check an error before show EMS price
 * if(!$rate->getError()){
 *     // And get EMS price rate
 *     $price = $rate->getPrice();
 * }
 * 
 * 
 * @author      Kritsanasak Kuntaros <roboconk@gmail.com>
 * @license	GNU General Public License version 2 or later; read license.txt
 * @since       version 1.0
 */
class RateTH{
    private $_weight;
    private $_price;
    private $_feed = "http://maxsitepro.com/ems.php";
    private $_ems_type = array(0=>"ems", "normal");
    private $_type;
    private $_error = FALSE;
    
    function __construct($weight=0, $type=0){
        $this->_weight = intval($weight);
        $this->_type = $this->_ems_type[$type];
        $this->calPrice();
    }
    
    /**
     * Get price from json
     */
    private function calPrice(){
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_feed);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $pre_ems = json_decode(curl_exec($ch), TRUE);
        curl_close($ch);
        
        $ems = $pre_ems[$this->_type];
        $ems_count = count($ems);
        
        if($pre_ems===FALSE || $pre_ems===NULL){
            $this->_error = "Connection lost please check your internet again.";
        }else if($ems===NULL){
            $this->_error = "Please select supply type \"0\" for EMS and type \"1\" for normal.";
        }else if($this->_weight === 0){
            $this->_error = "Your weight can not be zero, please check your item again.";
	}else if($this->_weight > $ems[$ems_count-1]['weight']){
            $this->_error = "Your weight is over the maximum limit.";
        }else{
            for($i=0; $i<$ems_count; $i++){
                $item = $ems[$i];
                $prevent_item = $ems[$i-1];
                if($prevent_item!==NULL && $this->_weight>$ems['0']['weight']){

                    if($this->_weight<=$item['weight'] && $this->_weight>$prevent_item['weight']){
                        $this->_price = $item['price'];
                    }
                }else if($prevent_item===NULL && $this->_weight===$ems['0']['weight']){
                    $this->_price = $item['price'];
                }
            } // End for
        }
    }
    
    /**
     * Get current EMS price from supply weight
     * 
     * @return int
     */
    public function getPrice(){
        if($this->_price!==NULL){
            return $this->_price;
        }else{
            return 0;
        }
    }
    
    /**
     * Check an error
     * 
     * @return boolean
     */
    public function getError(){
        if($this->_error!==FALSE){
            echo "<div>".$this->_error."</div>";
            return TRUE;
        }else{
            return FALSE;
        }
        
    }
}